package com.letianpai.common.tool;

import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.provider.MediaStore;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-3-26
 * Time: 下午5:30
 * To change this template use File | Settings | File Templates.
 */
public class ImageTool {
    //网络下载图片
    // // URL url = new URL("http://www.zhongtaisoft.com/ad.jpg");
    public static void downLoadImage(String location_address) {
        try {
            URL url = new URL(location_address);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoInput(true);
            con.connect();
            InputStream inputStream = con.getInputStream();
            inputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e
                ) {
            e.printStackTrace();
        }
    }

    public static String downLoadFileByURL(String urlStr) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        BufferedReader buffer = null;
        try {
// 创建一个URL对象
            urlStr = StringUtil.toUtf8(urlStr);
            URL url = new URL(urlStr);
// 创建一个Http连接
            HttpURLConnection urlConn = (HttpURLConnection) url
                    .openConnection();
// 使用IO流读取数据
            buffer = new BufferedReader(new InputStreamReader(
                    urlConn.getInputStream()));
            while ((line = buffer.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                buffer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    //网络读取图片
    //URL url = new URL("http://www.zhongtaisoft.com/ad.jpg");
    public static Bitmap readNetWorkImage(String location_address) {
        Bitmap bitmap = null;
        try {
            InputStream inputStream = readNetWorkImageToInputStream(location_address);
            //获取长度
            BitmapFactory.Options options = new BitmapFactory.Options();
//            opts.inJustDecodeBounds = true;
            bitmap = BitmapFactory.decodeStream(inputStream, null, options);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    //网络上获取 文件，图片 的InputStream
    public static InputStream readNetWorkImageToInputStream(String location_address) {
        InputStream inputStream = null;
        try {
            URL url = new URL(location_address.trim());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(600000);
            conn.connect();
            inputStream = conn.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    public static Bitmap readNetWorkImageBuHttpClient(String location_address) {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpGet = new HttpPost(location_address);
        Bitmap bitmap = null;
        try {
            HttpResponse response = httpClient.execute(httpGet);
            InputStream inputStream = response.getEntity().getContent();
            bitmap = BitmapFactory.decodeStream(inputStream);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return bitmap;
    }

    /**
     * **保存图片到本地*******
     */

    public static void saveBitmapToFile(Bitmap bitmap, String _file) {
        BufferedOutputStream os = null;
        try {
            File file = new File(_file);
            int end = _file.lastIndexOf(File.separator);
            String _filePath = _file.substring(0, end);
            File filePath = new File(_filePath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            file.createNewFile();
            os = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
        } catch (Exception e) {

        } finally {
            closeStream(null, os);
        }

    }

    /**
     * **保存图片到本地*******
     */

    public static boolean saveBitmapToFileJpg(Bitmap bitmap, String _file) {
        try {
            File file = new File(_file);
            File parent = file.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(file);
            int options = 90;
            boolean b = bitmap.compress(Bitmap.CompressFormat.JPEG, options, fos);
            while (isFileLarge(file)) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, options, fos);
                options -= 10;//每次都减少10
            }
            fos.flush();
            fos.close();
            return b;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    private static boolean isFileLarge(File file) {
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            if (fileInputStream.available() > 1024 * 200) {
//                file.delete();
                return true;
            }
        } catch (Exception e) {
        }
        return false;
    }

    //获取照相机拍照后的bitmap filename_path为该相片的保存路径和文件名，maxWidth为标准宽度值
    public static Bitmap compressPhoto(String path_name, int maxWidth) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmapImage = BitmapFactory.decodeFile(path_name, options); //获取图片的宽度和高度
        options.inJustDecodeBounds = false;
        int width = options.outWidth;
        if (width % maxWidth > (maxWidth / 2)) {
            options.inSampleSize = width / maxWidth + 1;
        } else {
            options.inSampleSize = width / maxWidth;
        }
        options.inTempStorage = new byte[16 * 1024];
        bitmapImage = BitmapFactory.decodeFile(path_name, options);
        return bitmapImage;
    }

    /**
     * 将Bitmap转换成指定大小
     */
    public static Bitmap createBitmapBySize(Bitmap bitmap, int width, int height) {
        return Bitmap.createScaledBitmap(bitmap, width, height, true);
    }

    public static Drawable getLocationDrawable(Context context, int draw_id) {
        try {
            return context.getResources().getDrawable(draw_id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 加载本地图片
     *
     * @param url
     * @return
     */
    public static Bitmap getLocalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * * 加载本地图片
     */
    public static Bitmap getLoacalBitmapByAssets(Context c, String fileName) {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
            in = c.getResources().getAssets().open(fileName);
            bitmap = BitmapFactory.decodeStream(in);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeStream(in, null);
        }
        return bitmap;
    }

    //Bitmap → byte[]
    public static byte[] bitmapWithPngToBytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    public static byte[] bitmapWithJpegToBytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return baos.toByteArray();
    }

    //byte[] → Bitmap
    public static Bitmap bytesToBitmap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }

    //Bitmap缩放
    public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) width / w);
        float scaleHeight = ((float) height / h);
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
        return newbmp;
    }

    //将Drawable转化为Bitmap
    public static Bitmap drawableToBitmap(Drawable drawable) {
        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }

    //获得圆角图片
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Bitmap output = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, w, h);
        final RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }

    //Bitmap转换成Drawable                         r
    public static Drawable convertToBitmap(Bitmap bm) {
        //xxx根据你的情况获取
        BitmapDrawable bd = new BitmapDrawable(bm);
        return bd;
        //因为BtimapDrawable是Drawable的子类，最终直接使用bd对象即可。

    }

    /*穿件带字母的标记图片
     * imgMarker 生成的图片
     * imgTemp 临时标记图
     * int width, int height 宽度 高度
     * letter 添加的文字
     */
    public static Drawable createDrawable(Resources resource, Bitmap imgMarker, int width, int height, String letter) {
        Bitmap imgTemp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(imgTemp);
        Paint paint = new Paint(); // 建立画笔
        paint.setDither(true);
        paint.setFilterBitmap(true);
        Rect src = new Rect(0, 0, width, height);
        Rect dst = new Rect(0, 0, width, height);
        canvas.drawBitmap(imgMarker, src, dst, paint);
        Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG
                | Paint.DEV_KERN_TEXT_FLAG);
        textPaint.setTextSize(22.0f);
        textPaint.setTypeface(Typeface.DEFAULT_BOLD); // 采用默认的宽度
        textPaint.setColor(Color.WHITE);
        //两个字
        if (letter.length() < 3) {
            canvas.drawText(letter, width / 2 - 25, height / 2,
                    textPaint);
        }
        if (letter.length() < 4 && letter.length() >= 3) {
            canvas.drawText(letter, width / 2 - 35, height / 2,
                    textPaint);
        }
        if (letter.length() < 5 && letter.length() >= 4) {
            canvas.drawText(letter, width / 2 - 45, height / 2,
                    textPaint);
        }
        if (letter.length() >= 5) {
            canvas.drawText(letter, width / 2 - 55, height / 2,
                    textPaint);
        }
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return (Drawable) new BitmapDrawable(resource, imgTemp);

    }

    /**
     * **在地图上创建店名******
     */
    public static Drawable createDrawableStoreName(Resources resource, Bitmap imgMarker, int width, int height, String letter) {
        Bitmap imgTemp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(imgTemp);
        Paint paint = new Paint(); // 建立画笔
        paint.setDither(true);
        paint.setFilterBitmap(true);
        Rect src = new Rect(0, 0, width, height);
        Rect dst = new Rect(0, 0, width, height);
        canvas.drawBitmap(imgMarker, src, dst, paint);
        Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG
                | Paint.DEV_KERN_TEXT_FLAG);
        textPaint.setTextSize(22.0f);
        textPaint.setTypeface(Typeface.DEFAULT_BOLD); // 采用默认的宽度
        textPaint.setColor(Color.WHITE);
        //两个字
        canvas.drawText(letter, 10, height / 2,
                textPaint);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return (Drawable) new BitmapDrawable(resource, imgTemp);

    }

    /**
     * **在地图上创建手机或座机号码*****
     */
    public static Bitmap createDrawablePhoneNumber(Resources resource, Bitmap imgMarker, int width, int height, String letter) {
        Bitmap imgTemp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(imgTemp);
        Paint paint = new Paint(); // 建立画笔
        paint.setDither(true);
        paint.setFilterBitmap(true);
        Rect src = new Rect(0, 0, width, height);
        Rect dst = new Rect(0, 0, width, height);
        canvas.drawBitmap(imgMarker, src, dst, paint);
        Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG
                | Paint.DEV_KERN_TEXT_FLAG);
        textPaint.setTextSize(22.0f);
        textPaint.setTypeface(Typeface.DEFAULT_BOLD); // 采用默认的宽度
        textPaint.setColor(Color.WHITE);
        //两个字
        canvas.drawText(letter, 10, height / 2,
                textPaint);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return imgTemp;

    }

    //Drawable缩放
    public static Drawable zoomDrawable(Drawable drawable, int w, int h) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        // drawable转换成bitmap
        Bitmap oldbmp = drawableToBitmap(drawable);
        // 创建操作图片用的Matrix对象
        Matrix matrix = new Matrix();
        // 计算缩放比例
        float sx = ((float) w / width);
        float sy = ((float) h / height);
        // 设置缩放比例
        matrix.postScale(sx, sy);
        // 建立新的bitmap，其内容是对原bitmap的缩放后的图
        Bitmap newbmp = Bitmap.createBitmap(oldbmp, 0, 0, width, height,
                matrix, true);

        return new BitmapDrawable(newbmp);
    }

    /**
     * 读取路径中的图片，然后将其转化为缩放后的bitmap
     */
    public static Bitmap getBitmapByLocationPath(String path) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeFile(path);
        } catch (Exception e) {
        }
        return bitmap;
    }

    public static Drawable getDrawableByLocationPath(String path) {
        Drawable drawable = null;
        try {
//            bitmap = BitmapFactory.decodeFile(path);
            drawable = Drawable.createFromPath(path);
        } catch (Exception e) {
        }
        return drawable;
    }

    /**
     * * 关闭输入输出流
     */
    public static void closeStream(InputStream in, OutputStream out) {
        try {
            if (null != in) {
                in.close();
            }
            if (null != out) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //计算图片的缩放值
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int h = options.outHeight;
        final int w = options.outWidth;
        int inSampleSize = 1;
        //图片按比例大小压缩方法
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            inSampleSize = (int) (w / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            inSampleSize = (int) (h / hh);
        }
        if (inSampleSize <= 0) {
            inSampleSize = 1;
        }
//        if (height > reqHeight || width > reqWidth) {
//            final int heightRatio = Math.round((float) height / (float) reqHeight);
//            final int widthRatio = Math.round((float) width / (float) reqWidth);
//            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
//        }
        return inSampleSize;
    }

    // 根据路径获得图片并压缩，返回bitmap用于显示
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);

    }

    //把bitmap转换成String
    public static byte[] imagePathToByte(String filePath) {
        Bitmap bitmap = getSmallBitmap(filePath);
        byte[] bytes = bitmapWithJpegToBytes(bitmap);
        return bytes;
    }

    /*读取照相图片，不压缩*/
    public static byte[] picturePathToByte(String image_path) {
        Bitmap bitmap = getLocalBitmap(image_path);
        byte[] bytes = bitmapWithJpegToBytes(bitmap);
        return bytes;
    }

    //根据路径id获得该路径下的所有文件名称
    /*
    * 其中 image_bucket_id 通过如下方法获得
    *  public static final String CAMERA_IMAGE_BUCKET_NAME =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString() + "/Camera";
    public static final String CAMERA_IMAGE_BUCKET_ID =
            getBucketId(CAMERA_IMAGE_BUCKET_NAME);
    public static String getBucketId(String path) {
        return String.valueOf(path.toLowerCase().hashCode());
    }
    */
    public static String getCameraImages(Context context, String image_bucket_id) {
        final String[] projection = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_ADDED, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.TITLE};
        final String selection = MediaStore.Images.Media.BUCKET_ID + " = ?";
        final String[] selectionArgs = {image_bucket_id};
        final Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection,
                selection,
                selectionArgs,
                MediaStore.Images.Media.DATE_ADDED + " DESC");
        String result = new String();
        if (cursor.moveToFirst()) {
            final int dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//            do {
//                final String data = cursor.getString(dataColumn);
//                result.add(data);
//            } while (cursor.moveToNext());
            result = cursor.getString(dataColumn);
        }
        cursor.close();
        return result;
    }

    /**
     * 霓虹效果
     *
     * @param bmp
     * @return
     */
    public static Bitmap neon(Bitmap bmp) {
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        int pixR = 0;
        int pixG = 0;
        int pixB = 0;
        int pixColor = 0;
        int pixColor1 = 0;
        int pixColor2 = 0;
        int pixR1 = 0;
        int pixG1 = 0;
        int pixB1 = 0;
        int pixR2 = 0;
        int pixG2 = 0;
        int pixB2 = 0;
        int newR = 0;
        int newG = 0;
        int newB = 0;
        int delta = 2;
        for (int i = 1, length = width - 1; i < length; i++) {
            for (int k = 1, len = height - 1; k < len; k++) {
                pixColor = bmp.getPixel(i, k);
                pixColor1 = bmp.getPixel(i + 1, k);
                pixColor2 = bmp.getPixel(i, k + 1);
                pixR = Color.red(pixColor);
                pixG = Color.green(pixColor);
                pixB = Color.blue(pixColor);
                pixR1 = Color.red(pixColor1);
                pixG1 = Color.green(pixColor1);
                pixB1 = Color.blue(pixColor1);
                pixR2 = Color.red(pixColor2);
                pixG2 = Color.green(pixColor2);
                pixB2 = Color.blue(pixColor2);
                newR = (int) (Math.sqrt(Math.pow(pixR - pixR1, 2) + Math.pow(pixR - pixR2, 2)) * delta);
                newG = (int) (Math.sqrt(Math.pow(pixG - pixG1, 2) + Math.pow(pixG - pixG2, 2)) * delta);
                newB = (int) (Math.sqrt(Math.pow(pixB - pixB1, 2) + Math.pow(pixB - pixB2, 2)) * delta);
                newR = Math.min(255, Math.max(0, newR));
                newG = Math.min(255, Math.max(0, newG));
                newB = Math.min(255, Math.max(0, newB));

                bitmap.setPixel(i, k, Color.argb(255, newR, newG, newB));
            }
        }
        return bitmap;
    }

    /**
     * 浮雕效果
     *
     * @param bmp
     * @return
     */
    public static Bitmap embossAmeliorate(Bitmap bmp) {
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);

        int pixR = 0;
        int pixG = 0;
        int pixB = 0;

        int pixColor = 0;

        int newR = 0;
        int newG = 0;
        int newB = 0;

        int[] pixels = new int[width * height];
        bmp.getPixels(pixels, 0, width, 0, 0, width, height);
        int pos = 0;
        for (int i = 1, length = height - 1; i < length; i++) {
            for (int k = 1, len = width - 1; k < len; k++) {
                pos = i * width + k;
                pixColor = pixels[pos];

                pixR = Color.red(pixColor);
                pixG = Color.green(pixColor);
                pixB = Color.blue(pixColor);

                pixColor = pixels[pos + 1];
                newR = Color.red(pixColor) - pixR + 127;
                newG = Color.green(pixColor) - pixG + 127;
                newB = Color.blue(pixColor) - pixB + 127;

                newR = Math.min(255, Math.max(0, newR));
                newG = Math.min(255, Math.max(0, newG));
                newB = Math.min(255, Math.max(0, newB));

                pixels[pos] = Color.argb(255, newR, newG, newB);
            }
        }

        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }

    //创建缩略图并返回路径
    public static boolean createThumbnail(String file_src_path, String file_target_path) {
        Bitmap bitmap = getSmallBitmap(file_src_path);
        boolean result = saveBitmapToFileJpg(bitmap, file_target_path);
        return result;
    }


}
